package com.bio;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.net.Socket;

public class BIOClient {

    public static void main(String agrs[]) {

        ByteArrayOutputStream output = null;
        try {

            int i = 1;
            while (true) {
                Socket socket = new Socket();
                System.out.println("start new Thread");
                new Thread(new ClientThread(socket, i)).start();
                i++;
                Thread.sleep(2000);
                if (i >=3) break;
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (output != null) {
                try {
                    output.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }


    static class ClientThread implements Runnable {

        private Socket cSocket;
        private int i;

        public ClientThread(Socket cSocket, int i) {
            super();
            this.cSocket = cSocket;
            this.i = i;
        }


        @Override
        public void run() {
            try {
                cSocket.connect(new InetSocketAddress(6666));
                OutputStream out = cSocket.getOutputStream();
                String con = "thread" + i + "\r\n";
                out.write(con.getBytes());
                Thread.sleep(1000);
                out.write("quit".getBytes());
                out.close();
                cSocket.close();

            } catch (Exception e) {
                try {
                    cSocket.close();
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
                e.printStackTrace();
            }
        }

    }

}